package DRC;

import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;

public class link_check {
    
    /**
     * 使用socket监测主机、端口是否可连接，可连接返回真，否则返回假
     * 超时默认1秒
     * @param host 地址
     * @param port 端口
     * @return
     */
    public static boolean socket_check(String host,int port){
        boolean result=false;
        Socket socket=new Socket();
        SocketAddress address=new InetSocketAddress(host, port);
        try {
            socket.connect(address, 1000);
            //获取Socket的输出流，用来向Slave端发送数据
            DataOutputStream out = new DataOutputStream (socket.getOutputStream());
            out.close();
            socket.close();
            result=true;
            // System.out.println("connected!");
        } catch (SocketTimeoutException e){
            return false;
        } catch (Exception e) {
            // e.printStackTrace();
            // System.out.println("can't connect!");
        }
        return result;
    }

    /**
     * 使用socket监测主机、端口是否可连接，可连接返回真，否则返回假
     * 增加超时设置参数
     * @param host 地址
     * @param port 端口
     * @param timeOut 毫秒 millisecond
     * @return
     */
    public static boolean socket_check(String host,int port,int timeOut){
        boolean result=false;
        Socket socket=new Socket();
        SocketAddress address=new InetSocketAddress(host, port);
        try {
            socket.connect(address, timeOut);
            //获取Socket的输出流，用来向Slave端发送数据
            DataOutputStream out = new DataOutputStream (socket.getOutputStream());
            out.close();
            socket.close();
            result=true;
            // System.out.println("connected!");
        } catch (SocketTimeoutException e){
            return false;
        } catch (Exception e) {
            // e.printStackTrace();
            // System.out.println("can't connect!");
        }
        return result;
    }

    public static void main(String[] args) {
        if(socket_check("127.0.0.1",502)){
            System.out.println("yes");
        }else{
            System.out.println("no");
        }
    }

}
